<script setup lang="ts">
import { useSendMobileCode } from '@/composable'
import { bindMobile, loginByQQ } from '@/services/user'
import { useUserStore } from '@/stores'
import { codeRules, mobileRules } from '@/utils/rules'
import { showSuccessToast } from 'vant'
import { ref } from 'vue'
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const userStore = useUserStore()

// 是否需要绑定手机
const isNeedBind = ref(false)

const openId = ref('')
onMounted(() => {
  /* global QC */
  if (QC.Login.check()) {
    QC.Login.getMe(async (id) => {
      openId.value = id
      try {
        const { data: user } = await loginByQQ(openId.value)
        userStore.saveUser(user)

        router.replace(
          (route.query.returnUrl as string) || { name: 'UserIndex' }
        )
        showSuccessToast('登录成功')
      } catch (err) {
        // 之前没有绑定过QQ登录（看能不能用openId登录，看有没有绑定过手机）
        isNeedBind.value = true
      }
    })
  } else {
    // 检查不通过，说明QQ登录不通过，去登录页
    router.replace({ name: 'LoginIndex' })
  }
})

const mobile = ref('')
const { refForm, time, send, code } = useSendMobileCode(mobile, 'bindMobile')

const onSubmit = async () => {
  console.log('[ onSubmit ] >')

  const { data: user } = await bindMobile(
    mobile.value,
    code.value,
    openId.value
  )
  userStore.saveUser(user)
  router.replace((route.query.returnUrl as string) || { name: 'UserIndex' })
  showSuccessToast('登录成功')
}
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="refForm" @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-model="code"
        :rules="codeRules"
        name="code"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>

<style lang="scss" scoped></style>
